from DataManagement.resource import ModelResource
from PeopleInfo.models import *
from import_export.fields import Field
import re

pattern = re.compile(r'\W+')


class EntranceGuardListResource(ModelResource):

    status_choice = {
        '准入': 1,
        '不准入': 2,
        '1': 1,
        '2': 2,
    }

    lock_choice = {
        '是': True,
        '否': False
    }

    class Meta:
        model = EntranceGuardList
        fields = ['id', 'username', 'nickname', 'level', 'status', 'reason', 'source', 'lock']
        skip_unchanged = True

        export_order = ['id', 'username', 'nickname', 'level', 'status', 'reason', 'source', 'lock']
        import_id_fields = ['id']

    id = Field(attribute='id', column_name='编号')
    username = Field(attribute='username', column_name='学工号')
    nickname = Field(attribute='nickname', column_name='姓名')
    level = Field(attribute='level', column_name='权限级别')
    status = Field(attribute='status', column_name='状态')
    reason = Field(attribute='reason', column_name='原因')
    source = Field(attribute='source', column_name='数据来源')
    lock = Field(attribute='lock', column_name='是否锁定')

    def before_import_row(self, row, **kwargs):
        username = row.get('学工号')
        if not row.get('编号'):
            item = EntranceGuardList.objects.filter(username=username).first()
            if item:
                row['编号'] = item.id

        row['学工号'] = re.sub(pattern, '', username)
        status = row.get('状态')
        lock = row.get('是否锁定')
        if status in self.status_choice.keys():
            row['状态'] = self.status_choice[status]
        if lock in self.lock_choice.keys():
            row['是否锁定'] = self.lock_choice[lock]

        super().before_import_row(row, **kwargs)

    def before_save_instance(self, instance, using_transactions, dry_run):
        super().before_save_instance(instance, using_transactions, dry_run)

    def save_instance(self, instance, using_transactions=True, dry_run=False):
        super().save_instance(instance, using_transactions, dry_run)



